home *** CD-ROM | disk | FTP | other *** search
- Path: info.spt.net.cn!usenet
- From: txwang@public.sta.net.cn (Wang TianXing)
- Newsgroups: comp.lang.c++
- Subject: Re: Overloading conversion
- Date: Wed, 24 Jan 1996 18:00:01 GMT
- Organization: No Organization
- Distribution: world
- Message-ID: <4e5r4t$41f@info.sta.net.cn>
- References: <4d934v$10hs@ds2.acs.ucalgary.ca> <4e1a0v$dvh@hpbab.wv>
- NNTP-Posting-Host: ts2-10.sta.net.cn
- X-Newsreader: Forte Free Agent 1.0.82
-
- bloom@wv.mentorg.com (Scott Aron Bloom) wrote:
-
- | In article <4d934v$10hs@ds2.acs.ucalgary.ca>, hdang@acs3.acs.ucalgary.ca (Hanna Dang) writes:
- | |> Is there a way to overload functions such that certain
- | |> functions are called depending on the context the object are
- | |> used. For example,
- | |>
- | |> class T {
- | |> public:
- | |> int& int_value() { modified = TRUE; return value;}
- | |> int int_value() {return value;}
- | |> private:
- | |> int value;
- | |> int modified;
- | |> }
- | |>
- | |>
- | |> ...
- | |>
- | |> T a;
- | |> int test = a + 6 // int int_value should be called;
- | |> a = 20 // int& int_value should be called.
- | |>
- | |> However, this does not work because in both case int& int_value
- | |> is called. Is there another way to find out if value is changed
- | |> or it's just inspected.
- | |>
-
-
- | To tell you the truth, I am kinda shocked that class T compiled
- | at all.
- Yes, it should not be compiled.
-
- | And this is what i would expect. Remember, return values from functions in
- | C/C++ are not required to be used. Therefor you can not overload in C++
- | based off of the return type.
-
- | What you really want is something like PASCAL has, the procedure/function
- | difference.
-
- | While I have tried to figure out ways to do what you want, I usually
- | give up. The method I sometimes use is having a member function T::value().
-
- | So for your code you would use
-
- | T a;
- | int test = a.value + 6;
- | a = 20;
-
-
- | Sorry to be the bearer of bad news...
-
- But, try this, please:
-
- class T {
- public:
- T( int v = 0 ) : value(v), modified(0) {}
-
- operator int() { return value; }
- int operator =( int v ) { modified = 1; return value = v; }
-
- private:
- int value;
- int modified;
- };
-
- int main()
- {
- T a(30);
-
- int test = a + 6; // int() should be called
- a = 20; // =(int) should be called
-
- return 0;
- }
-
- ---
- Wang TianXing
-
-
-